package controllers

import (
	"encoding/base64"
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"smart_home/api/models"
	"smart_home/api/xfyun/cloud"
	"smart_home/api/xfyun/depots"
	"smart_home/api/xfyun/voice"
)

type XfyunController struct {
	BaseController
}

// @Title 云函数
// @Description 操作设备
// @router /cloud [post]
func (c *XfyunController) Cloud() {
	var (
		rq         *depots.Request
		err        error
		res        *depots.XfyunResult
		userParams = &cloud.UserParams{}
		dc         []byte
	)

	res = &depots.XfyunResult{
		IsEnd:    true,
		IsHandle: false,
		Answer:   "哎呀，一不小心没听清，请再说一遍吧",
		Data:     make(map[string]interface{}),
	}

	defer c.Success(res)
	logs.Debug("body:", string(c.Ctx.Input.RequestBody))
	rq = &depots.Request{}
	if err = json.Unmarshal(c.Ctx.Input.RequestBody, rq); err != nil {
		logs.Error("Cloud:", err, string(c.Ctx.Input.RequestBody))
		res.Answer = "系统发生错误，请再试一次吧"
		return
	}

	if len(rq.Context.Private.Userparams) > 0 {
		if dc, err = base64.StdEncoding.DecodeString(rq.Context.Private.Userparams); err != nil {
			logs.Error("Cloud:", err)
			res.Answer = "系统发生错误，请再试一次吧"
			return
		}
		if err = json.Unmarshal(dc, userParams); err != nil {
			logs.Error("Cloud:", err, string(dc))
			res.Answer = "系统发生错误，请再试一次吧"
			return
		}
	} else { // 测试用例
		userParams.UserId = "5b554c2dc175f4272e7d0e52"
		userParams.Sta = "dc4f2252fd7a"
		userParams.DeviceType = 1
	}

	if len(userParams.UserId) == 0 {
		logs.Error("Cloud err: user_id is null")
		res.Answer = "系统发生错误，请再试一次吧"
		return
	}

	if userParams.User, err = models.GetUserById(userParams.UserId); err != nil {
		logs.Error("Cloud err:", err)
		res.Answer = "系统发生错误，请再试一次吧"
		return
	}

	res.Data["uid"] = userParams.UserId
	if len(userParams.Sta) > 0 {
		res.Data["sta"] = userParams.Sta
	}

	// 默认设备类型为app
	res.Data["device_type"] = userParams.DeviceType

	logs.Debug("userparams: %+v", userParams)
	logs.Debug("%+v", rq)

	if len(rq.Request.Intents) > 0 && len(rq.Request.Intents[0].Name) > 0 {
		if err = cloud.RunCloud(rq.Request.Intents[0].Name, rq, res, userParams); err != nil {
			logs.Error("Cloud:", err)
			res.Answer = "系统发生错误，请再试一次吧"
			return
		}
	}
}

// @Title 语音
// @Description 语音解析控制
// @router /voice/parser [post]
func (c *XfyunController) Parser() {
	sta := c.Ctx.Input.Header("sta")
	order := c.Ctx.Input.Header("order")
	status := c.Ctx.Input.Header("status")
	body := c.Ctx.Input.RequestBody

	if status == "begin" {
		voice.Begin(sta, order, body)
	}
	if status == "reading" {
		voice.Queue(sta, order, body)
	}
	if status == "end" {
		voice.End(sta, order, body)
	}
}
